
import Pool from './base/pool';

let instance;

/**
 * 全局状态管理器
 */
export default class DataBus {
  constructor() {
    if (instance) return instance;

    instance = this;

    this.pool = new Pool();

    this.reset();
  }

  reset() {
    this.frame = 0;
    this.score = 0;
    this.distance = 0;     // 行进距离
    this.waves = 0;        // 通过的波次
    this.enemies = [];
    this.bullets = [];     // 添加bullets数组
    this.animations = [];
    this.attackEffects = []; // 攻击效果
    this.captureTexts = []; // 捕获提示文本
    this.gameOver = false;
    this.gamePaused = false; // 游戏暂停状态
    this.player = null;    // 将在CharacterManager中设置
    this.music = null;     // 将在main.js中设置
    this.screenWidth = 0;  // 将在main.js中设置
    this.screenHeight = 0; // 将在main.js中设置
    this.debug = false;    // 调试模式，显示攻击区域等
    this.showLeaderboard = false; // 是否显示排行榜
    this.leaderboardData = []; // 排行榜数据
    this.scoreUploaded = false; // 分数是否已上传
    this.recordManager = null; // 录制管理器
    this.isRecording = false; // 是否正在录制
    
    // 捕猎统计
    this.huntingStats = {
      lion: { goats: 0, pigs: 0, hunger: 100 },
      allies: []  // 盟友的捕猎统计将在添加盟友时初始化
    };
  }

  /**
   * 设置游戏结束状态
   */
  setGameOver() {
    this.gameOver = true;
    
    // 停止录制
    if (this.isRecording && this.recordManager) {
      this.recordManager.stopRecording();
      this.isRecording = false;
      console.log('游戏结束，停止录制');
    }
  }

  /**
   * 添加捕获提示
   * @param {string} text - 提示文本
   * @param {number} x - x坐标
   * @param {number} y - y坐标
   */
  addCaptureText(text, x, y, enemy) {
    const captureText = {
      x: x,
      y: y - 30,
      text: `恭喜！捕获${text}一头`,
      color: '#FFFF00',
      fontSize: 16,
      alpha: 1.0,
      lifeTime: 300, // 显示5秒(300帧)
      enemy: enemy, // 保存被捕获的敌人引用
      scale: 1.0,   // 初始缩放比例
      growing: true, // 是否正在放大
      update() {
        if (this.growing) {
          // 放大效果
          this.scale += 0.02;
          if (this.scale >= 2.0) {
            this.growing = false;
          }
        } else {
          // 缓慢上升并逐渐消失
          this.y -= 0.5;
          this.alpha -= 1 / this.lifeTime;
        }
        return this.alpha > 0;
      },
      render(ctx) {
        ctx.save();
        
        // 绘制敌人图像(放大)
        if (this.enemy && this.enemy.img) {
          const imgWidth = this.enemy.width * this.scale;
          const imgHeight = this.enemy.height * this.scale;
          const imgX = this.x - imgWidth / 2;
          const imgY = this.y - imgHeight - 10;
          
          ctx.globalAlpha = this.alpha;
          ctx.drawImage(
            this.enemy.img,
            this.enemy.sx, this.enemy.sy,
            this.enemy.width, this.enemy.height,
            imgX, imgY,
            imgWidth, imgHeight
          );
        }
        
        // 绘制文字
        ctx.font = `${this.fontSize}px Arial`;
        ctx.fillStyle = this.color;
        ctx.globalAlpha = this.alpha;
        ctx.textAlign = 'center';
        ctx.fillText(this.text, this.x, this.y);
        
        ctx.restore();
      }
    };
    
    this.captureTexts.push(captureText);
  }

  /**
   * 暂停游戏
   * @param {number} duration - 暂停时长(毫秒)
   */
  pauseGame(duration) {
    this.gamePaused = true;
    setTimeout(() => {
      this.gamePaused = false;
    }, duration);
  }

  /**
   * 更新游戏统计数据
   * @param {number} distance - 新增距离
   */
  updateStats(distance) {
    this.distance += distance;
    // 每100距离算作一波
    this.waves = Math.floor(this.distance / 100);
  }

  /**
   * 游戏结束时上传分数
   */
  async uploadScore() {
    if (window.cloudManager) {
      await window.cloudManager.uploadScore(
        this.score,
        Math.floor(this.distance),
        this.waves
      );
    }
  }

  /**
   * 回收敌人，进入对象池
   * 此后不进入帧循环
   */
  removeEnemy(enemy) {
    const index = this.enemies.indexOf(enemy);
    if (index !== -1) {
      this.enemies.splice(index, 1);
    }

    enemy.visible = false;

    this.pool.recover('enemy', enemy);
  }

  /**
   * 回收子弹，进入对象池
   * 此后不进入帧循环
   */
  removeBullets(bullet) {
    const index = this.bullets.indexOf(bullet);
    if (index !== -1) {
      this.bullets.splice(index, 1);
    }

    bullet.visible = false;

    this.pool.recover('bullet', bullet);
  }

  /**
   * 获取排行榜数据
   */
  async getLeaderboardData() {
    try {
      if (window.cloudManager) {
        // 获取排行榜数据
        const data = await window.cloudManager.getLeaderboard();
        this.leaderboardData = data.map(item => ({
          nickname: item.nickname || '玩家',
          score: item.score || 0,
          distance: item.distance || 0,
          waves: item.waves || 0
        }));
        
        // 按分数降序排序
        this.leaderboardData.sort((a, b) => b.score - a.score);
      } else {
        console.warn('cloudManager not found, using mock data');
        // 使用模拟数据用于测试
        this.leaderboardData = [
          { nickname: '测试玩家1', score: 1000, distance: 500, waves: 5 },
          { nickname: '测试玩家2', score: 800, distance: 400, waves: 4 },
          { nickname: '测试玩家3', score: 600, distance: 300, waves: 3 }
        ];
      }
    } catch (error) {
      console.error('Failed to get leaderboard data:', error);
      this.leaderboardData = [];
    }
  }

  /**
   * 上传分数到云开发
   */
  async uploadScore() {
    try {
      if (window.cloudManager) {
        await window.cloudManager.uploadScore({
          score: this.score,
          distance: this.distance,
          waves: this.waves
        });
        console.log('Score uploaded successfully');
      } else {
        console.warn('cloudManager not found, score not uploaded');
      }
    } catch (error) {
      console.error('Failed to upload score:', error);
    }
    this.scoreUploaded = true;
  }

  /**
   * 更新游戏状态
   */
  update() {
    this.frame++;
    
    // 每300帧(约5秒)减少饥饿度
    if (!this.gameOver && this.frame % 300 === 0) {
      // 减少主角狮子的饥饿度
      this.huntingStats.lion.hunger = Math.max(0, this.huntingStats.lion.hunger - 1);
      
      // 减少盟友的饥饿度
      if (this.allies) {
        this.allies.forEach((ally, index) => {
          if (!this.huntingStats.allies[index]) {
            this.huntingStats.allies[index] = { goats: 0, pigs: 0, hunger: 100 };
          }
          this.huntingStats.allies[index].hunger = Math.max(0, this.huntingStats.allies[index].hunger - 1);
        });
      }
      
      // 应用饥饿度效果
      this.applyHungerEffects();
    }
  }
  
  /**
   * 应用饥饿度效果
   */
  applyHungerEffects() {
    // 主角狮子饥饿度效果
    if (this.player) {
      const hungerFactor = this.huntingStats.lion.hunger / 100;
      this.player.attackModifier = 0.5 + (hungerFactor * 0.5); // 饥饿时攻击力降低50%
      this.player.speedModifier = 0.7 + (hungerFactor * 0.3);  // 饥饿时速度降低30%
    }
    
    // 盟友饥饿度效果
    if (this.allies) {
      this.allies.forEach((ally, index) => {
        if (this.huntingStats.allies[index]) {
          const hungerFactor = this.huntingStats.allies[index].hunger / 100;
          ally.attackModifier = 0.5 + (hungerFactor * 0.5);
          ally.speedModifier = 0.7 + (hungerFactor * 0.3);
        }
      });
    }
  }
}